package com.easylinkin.linkappapi.quality.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.quality.dto.QualityInspectionDTO;
import com.easylinkin.linkappapi.quality.entity.QualityInspection;
import com.easylinkin.linkappapi.quality.mapper.QualityInspectionMapper;
import com.easylinkin.linkappapi.quality.service.QualityInspectionService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.tenant.entity.LinkappTenant;
import com.easylinkin.linkappapi.tenant.mapper.LinkappTenantMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 闸机表 服务实现类
 * </p>
 *
 * @author TongJie
 * @since 2022-04-13
 */
@Service
public class QualityInspectionServiceImpl extends ServiceImpl<QualityInspectionMapper, QualityInspection> implements QualityInspectionService {

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;
  @Resource
  private LinkappTenantMapper linkappTenantMapper;

  /**
   * 增加
   * @param qualityInspection
   */
  @Override
  public void insert(QualityInspection qualityInspection) {
    /**
     * 验证重复
     */
//    this.checkExist(qualityInspection);
    //设置基本属性
    this.setBase(qualityInspection);
    this.save(qualityInspection);
  }

  /**
   * 根据id编辑
   * @param qualityInspection
   */
  @Override
  public void updateOne(QualityInspection qualityInspection) {
    /**
     * 验证重复
     */
//    this.checkExist(qualityInspection);
    //设置基本属性
    this.setBase(qualityInspection);
    this.updateById(qualityInspection);
  }

  @Override
  public IPage<QualityInspectionDTO> queryListByPage(RequestModel<QualityInspectionDTO> requestModel) {
    Page page = requestModel.getPage();
    QualityInspectionDTO qualityInspectionDTO = requestModel.getCustomQueryParams();
    if (null != qualityInspectionDTO.getStartTime()){
      qualityInspectionDTO.setStartTime(DateUtil.beginOfDay(qualityInspectionDTO.getStartTime()));
    }
    if (null != qualityInspectionDTO.getEndTime()){
      qualityInspectionDTO.setEndTime(DateUtil.endOfDay(qualityInspectionDTO.getEndTime()));
    }
    //项目id 过滤
    qualityInspectionDTO.setCreatorId(linkappUserContextProducer.getCurrent().getId());
    qualityInspectionDTO.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    IPage<QualityInspectionDTO> qualityInspectionIPage = baseMapper.queryListByPage(page, qualityInspectionDTO);
    return qualityInspectionIPage;
  }

  @Override
  public IPage<QualityInspectionDTO> queryListByPageFromEnterprise(RequestModel<QualityInspectionDTO> requestModel) {
    Page page = requestModel.getPage();
    QualityInspectionDTO qualityInspectionDTO = requestModel.getCustomQueryParams();
    if (null != qualityInspectionDTO.getStartTime()){
      qualityInspectionDTO.setStartTime(DateUtil.beginOfDay(qualityInspectionDTO.getStartTime()));
    }
    if (null != qualityInspectionDTO.getEndTime()){
      qualityInspectionDTO.setEndTime(DateUtil.endOfDay(qualityInspectionDTO.getEndTime()));
    }

    // 处理projectIds 项目过滤 用户所拥有权限的项目下的数据
    Set<Long> projectIds = qualityInspectionDTO.getProjectIds();
    if (ObjectUtils.isEmpty(projectIds)) {
      return page;
    }
    List<LinkappTenant> tenants2 = linkappTenantMapper.selectByProjectIds(projectIds);
    Set<String> tenantIds2 = tenants2.stream().map(LinkappTenant::getId).collect(Collectors.toSet());
    if (ObjectUtils.isEmpty(tenantIds2)) {
      return page;
    }
    qualityInspectionDTO.setTenantIds(tenantIds2);


    // 处理项目过滤
    if (qualityInspectionDTO.getProjectId() != null) {
      List<LinkappTenant> tenants = linkappTenantMapper.selectByProjectId(String.valueOf(qualityInspectionDTO.getProjectId()));
      if (tenants.size() == 0) {
        return page;
      } else {
        qualityInspectionDTO.setTenantId(tenants.get(0).getId());
      }
    }
    IPage<QualityInspectionDTO> qualityInspectionIPage = baseMapper.queryListByPage(page, qualityInspectionDTO);
    Set<String> tenantIds = qualityInspectionIPage.getRecords().stream().map(QualityInspectionDTO::getTenantId).collect(Collectors.toSet());

    List<LinkappTenant> tenants = linkappTenantMapper.selectProjectNamesByTenantIds(tenantIds);
    Map<String, List<LinkappTenant>> map = tenants.stream().collect(Collectors.groupingBy(LinkappTenant::getId));

    for (QualityInspectionDTO record : qualityInspectionIPage.getRecords()) {
      // 设置项目名称
      List<LinkappTenant> list = map.get(record.getTenantId());
      if (list != null && list.size() != 0) {
        record.setProjectName(list.get(0).getPlatformProjectName());
      }
    }
    return qualityInspectionIPage;
  }

  /**
   * 验证重复
   */
  private void checkExist(QualityInspection qualityInspection) {
    QueryWrapper<QualityInspection> queryWrapper = new QueryWrapper<>();
    //todo 设置判断重复条件
    queryWrapper.eq("tenant_id_",linkappUserContextProducer.getNotNullCurrent().getTenantId());
    //编辑的时候存在id
    Optional.ofNullable(qualityInspection.getId()).ifPresent(id -> queryWrapper.ne("id",qualityInspection.getId()));
    Integer integer = baseMapper.selectCount(queryWrapper);
    if (integer>0){
      throw new BusinessException("该巡检记录已存在");
    }
  }

  /**
   * 设置基本属性
   * @param qualityInspection
   */
  private void setBase(QualityInspection qualityInspection) {
    qualityInspection.setModifyTime(new Date());
    qualityInspection.setModifyId(linkappUserContextProducer.getCurrent().getId());
    //没有id就是新增,有就是编辑
    if (null == qualityInspection.getId()){
      qualityInspection.setCreatorId(linkappUserContextProducer.getCurrent().getId());
      qualityInspection.setCreateTime(new Date());
      qualityInspection.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    }
  }
}
